package  
{
	import flash.display.Sprite;
	import flash.geom.Vector3D;
	
	/**
	 * ...
	 * @author Guillaume Sylvain
	 */
	public class Boid extends Sprite
	{
		private const SLOWING_RANGE:int = 40;
		
		public var mFriend:Boid 	= null;
		public var mEnemy:Boid 		= null;
		
		private var mSpeed:Number 	= 8;
		private var mBind:Sprite 	= new Sprite();
		private var mVec:Vector3D 	= new Vector3D();
		
		public function Boid() 
		{
			this.graphics.beginFill(0xff0000);
			this.graphics.drawCircle(0, 0, 3);
			this.graphics.endFill();
			this.cacheAsBitmap = true;
			
			mSpeed += Math.random() - 0.5;
		}
		
		public function Update():void
		{
			Move(mFriend, 2 * mSpeed);
			Move(mEnemy, -1 * mSpeed);
			MoveToBind(mBind, 0.5 * mSpeed);
		}
		
		private function MoveToBind(aTarget:Sprite, aSpeed:Number):void
		{
			mVec.x = aTarget.x - x;
			mVec.y = aTarget.y - y;
			
			mVec.normalize();
			mVec.scaleBy(aSpeed);
			
			x += mVec.x;
			y += mVec.y;
		}
		
		private function Move(aTarget:Sprite, aSpeed:Number):void 
		{
			mVec.x = aTarget.x - x;
			mVec.y = aTarget.y - y;
			
			// The closer to the target, the slower the speed.
			// This really helps creating a swarm effect.
			if (mVec.length < SLOWING_RANGE)
			{
				aSpeed *= mVec.length / SLOWING_RANGE;
			}
			
			mVec.normalize();
			mVec.scaleBy(aSpeed);
			
			x += mVec.x;
			y += mVec.y;
		}
		
		public function SetBindPos(aX:Number, aY:Number):void
		{
			mBind.x = aX;
			mBind.y = aY;
		}
	}
}